package com.cqupt.slewing

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.cqupt.slewing.room.Item
import org.json.JSONObject

class MyViewModel(application: Application) : AndroidViewModel(application) {
    private val myRepository = MyRepository(application)

    suspend fun userLogin(
        username: String,
        password: String,
        remember: Boolean
    ): String {
        val json = JSONObject()
        json.put("username", username)
        json.put("password", password)
        json.put("remember", remember)

        return myRepository.login(json.toString())
    }

    suspend fun userRegister(
        username: String,
        password: String,
    ): Boolean {
        val json = JSONObject()
        json.put("username", username)
        json.put("password", password)
        return myRepository.postData("user/register", json.toString())
    }

    suspend fun userLogout(): Boolean {
        return myRepository.logout()
    }

    suspend fun getDevLocation(macID: String): String {
        val result = myRepository.getData("device/get_distance/$macID")
        val json = JSONObject(result)
        val d1 = json.getDouble("d1")
        val d2 = json.getDouble("d2")
        val d3 = json.getDouble("d3")

        return "d1=$d1, d2=$d2, d3=$d3"
    }

    suspend fun getAllDevice(): List<Item> {
        val devices: ArrayList<Item> = arrayListOf()

        val result = myRepository.getData("/user/myDevices")
        val json = JSONObject(result)
        val dev = json.getJSONObject("dev")
        val count = json.getInt("total")

        for (i in 1..count) {
            val macID = dev.getString("dev$i")
            val item = Item(macID)
            devices.add(item)
        }
        return devices
    }

    suspend fun bindDevice(macID: String) {
        myRepository.getData("user/add_dev/$macID")
    }

    suspend fun popDevice(macID: String) {
        myRepository.getData("user/delete_dev/$macID")
    }

    /**
     * 三角定位
     */
    fun triangulation(d1: Double, d2: Double, d3: Double) {

    }
}